package com.letianpai.activity.photoalbum;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.*;
import com.letianpai.R;
import com.letianpai.adapter.photoalbum.HomePhotoAdapter;
import com.letianpai.adapter.photoalbum.HomePhotoBean;
import com.letianpai.common.server.ResultBean;
import com.letianpai.common.server.ServerInterface;
import com.letianpai.common.server.ServerTool;
import com.letianpai.common.tool.StringUtil;
import com.letianpai.db.cache.PhotoAlbumCache;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 14-9-25
 * Time: 上午11:22
 * 家园相册
 */
public class HomeLandPhotoActivity extends Activity {
    private ListView photoInfoLv;
    private HomePhotoAdapter photoAdapter;
    private String roomId;
    private String username;
    private RelativeLayout bottomRl;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.home_land_photo);
        photoInfoLv = (ListView) findViewById(R.id.home_photo_info_lv);
        ImageButton backIb = (ImageButton) findViewById(R.id.top_back_ib);
        backIb.setOnClickListener(new PhotoClickListener('E'));
        TextView createAlbumTv = (TextView) findViewById(R.id.home_create_album_tv);
        createAlbumTv.setOnClickListener(new PhotoClickListener('C'));
        TextView deleteAlbumTv = (TextView) findViewById(R.id.home_delete_album_tv);
        deleteAlbumTv.setOnClickListener(new PhotoClickListener('D'));
        bottomRl = (RelativeLayout) findViewById(R.id.home_land_photo_bottom_rl);
        TextView deletePhotoAlbumTv = (TextView) findViewById(R.id.home_land_photo_delete_tv);
        deletePhotoAlbumTv.setOnClickListener(new DeletePhotoAlbumListener());
        //加载家园相册
        Intent intent = getIntent();
        roomId = intent.getStringExtra("roomid");
        username = intent.getStringExtra("username");
        initPhoto(false);
        IntentFilter intentfilter = new IntentFilter();
        //为IntentFilter对象添加Action，也相当于在AndroidManifest.xml定义一样，定义的目的是过滤器只许当安卓的操作系统产生短消息的事件咱们自定义的这个BroadcastReceiver类才能来接收短消息这个广播，我们才能进行代码的进一步处理
        intentfilter.addAction("com.letianpai.album.action.broadcast");
        //注册广播接收器
        registerReceiver(new AlbumReceiver(), intentfilter);
    }


    private void initPhoto(boolean delete) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("roomid", roomId);
        map.put("action", "get");
        ServerTool.getInstance().methodPost(this, "roomPhotoCategoryServlet", map, new PhotoListener(delete));
    }


    class PhotoListener implements ServerInterface {
        boolean delete;

        PhotoListener(boolean delete) {
            this.delete = delete;
        }

        @Override
        public void gainData(ResultBean bean) {
            if (bean.isSuccess()) {
                List<HomePhotoBean> photoList = new ArrayList<HomePhotoBean>();
                try {
                    JSONArray array = new JSONArray(bean.getResultContent());
                    int count = array.length();
                    for (int i = 0; i < count; i++) {
                        JSONObject obj = array.getJSONObject(i);
                        HomePhotoBean photo = new HomePhotoBean();
                        photo.setHomeTitle(obj.getString("catname"));
                        photo.setNumber(obj.getString("num"));
                        photo.setTime(obj.getString("creationdate"));
                        photo.setUploadPeople(obj.getString("owner"));
                        photo.setImageUrl(obj.getString("album"));
                        photo.setAlbumId(obj.getString("catid"));
                        int is_public = obj.getInt("is_public");
                        if (0 == is_public) {
                            photo.setWhetherPublic(false);
                        } else {
                            photo.setWhetherPublic(true);
                        }
                        if (delete) {
                            //不是默认相册，且是本人创建的
                            if ((username.equals(photo.getUploadPeople())) && (false == photo.isWhetherPublic())) {
                                photoList.add(photo);
                            }
                        } else {
                            photoList.add(photo);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                photoAdapter = new HomePhotoAdapter(HomeLandPhotoActivity.this, roomId, username, delete, photoList);
                photoInfoLv.setAdapter(photoAdapter);
            }
        }
    }


    private class PhotoClickListener implements View.OnClickListener {
        char type;

        private PhotoClickListener(char type) {
            this.type = type;
        }

        @Override
        public void onClick(View v) {
            switch (type) {
                case 'C': {
                    Intent intent = new Intent(HomeLandPhotoActivity.this, CreateAlbumActivity.class);
                    intent.putExtra("username", username);
                    intent.putExtra("roomid", roomId);
                    startActivityForResult(intent, 20000);
                    break;
                }

                case 'H': {
                    //家庭相册
                    Intent intent = new Intent(HomeLandPhotoActivity.this, NewAlbumActivity.class);
                    intent.putExtra("username", username);
                    intent.putExtra("roomid", roomId);
                    startActivityForResult(intent, 20000);
                    break;
                }
                case 'D': {
                    if (bottomRl.getVisibility() == View.VISIBLE) {
                        initPhoto(false);
                        bottomRl.setVisibility(View.GONE);
                    } else {
                        initPhoto(true);
                        bottomRl.setVisibility(View.VISIBLE);
                    }
                    break;
                }
                case 'E': {
                    finish();
                    break;
                }

            }
        }

    }

//删除操作

    class DeletePhotoAlbumListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            Set<String> sets = PhotoAlbumCache.getPhotoAlbum(HomeLandPhotoActivity.this);
            String albumIdArray = "";
            for (String str : sets) {
                albumIdArray = albumIdArray + str + ",";
            }
            if (StringUtil.isNotBlank(albumIdArray)) {
                albumIdArray = albumIdArray.substring(0, albumIdArray.length() - 1);
            }
            Map<String, String> maps = new HashMap<String, String>();
            maps.put("action", "del");
            maps.put("roomid", roomId);
            maps.put("username", username);
            maps.put("catname", albumIdArray);
            ServerTool.getInstance().methodPost(HomeLandPhotoActivity.this, "roomPhotoCategoryServlet", maps, new DeletePhotoAlbumRealize());
        }
    }

    class DeletePhotoAlbumRealize implements ServerInterface {

        @Override
        public void gainData(ResultBean bean) {
            if (bean.isSuccess()) {
                PhotoAlbumCache.movePhotoAlbumAll(HomeLandPhotoActivity.this);
                //刷新列表
                bottomRl.setVisibility(View.GONE);
                initPhoto(false);
            } else {
                Toast.makeText(HomeLandPhotoActivity.this, "服务忙，请您稍后再试", Toast.LENGTH_LONG).show();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            if (20000 == requestCode) {
                String result = data.getExtras().getString("refresh");
                if ("create_album_return".equals(result)) {
                    initPhoto(false);
                }
                if ("new_album_return".equals(result)) {
                    initPhoto(false);
                }

            }
        }
    }

    public class AlbumReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (action.equals("com.letianpai.album.action.broadcast")) {
                initPhoto(false);
            }
        }
    }
}